#include "Ctrl.h"
#include "CtrlConfig.h"

#define HAS_PWM1 (defined(SC95FWxx))

static uint8_t _getPWMx_Type(uint8_t PWMxy)
{
    return (PWMxy >> 4);
}

static uint8_t _getPWMx(uint8_t PWMxy)
{
    uint8_t x = (PWMxy >> 4);
    return (1 << x);
}

void Ctrl_init()
{
    uint8_t PWMx_Type = _getPWMx_Type(WATEROPEN_PWM);
    uint16_t PWM_Period;
    PWM_PresSel_TypeDef PWM_PRESSEL_FHRC;
    switch (PWMx_Type)
    {
    case 0:
        PWM_Period = 4000000/WATEROPEN_PWM_FREQ;
        PWM_PRESSEL_FHRC = PWM0_PRESSEL_FHRC_D8;
        break;
    #if HAS_PWM1
    case 1:
        PWM_Period = 4000000/WATEROPEN_PWM_FREQ;
        PWM_PRESSEL_FHRC = PWM1_PRESSEL_FHRC_D8;
        break;
    #endif
    case 2:
        PWM_Period = 32000000/WATEROPEN_PWM_FREQ;
        PWM_PRESSEL_FHRC = PWM2_PRESSEL_FHRC_D1;
        break;
    case 3:
        PWM_Period = 32000000/WATEROPEN_PWM_FREQ;
        PWM_PRESSEL_FHRC = PWM3_PRESSEL_FHRC_D1;
        break;
    }
    PWM_Init(PWM_PRESSEL_FHRC, PWM_Period);
    PWM_OutputStateConfig(WATEROPEN_PWM, PWM_OUTPUTSTATE_ENABLE);
    PWM_PolarityConfig(WATEROPEN_PWM, PWM_POLARITY_NON_INVERT);
    PWM_IndependentModeConfig(WATEROPEN_PWM, PWM_Period/2);


    GPIO_Init(FOODCTRL_Port, FOODCTRL_Pin, GPIO_MODE_OUT_PP);
}

void Ctrl_foodOpen(bool state)
{
    if(state)
    {
        GPIO_WriteHigh(FOODCTRL_Port, FOODCTRL_Pin);
    }
    else
    {
        GPIO_WriteLow(FOODCTRL_Port, FOODCTRL_Pin);
    }
}

void Ctrl_waterOpen(uint16_t speed)
{
    PWM_IndependentModeConfig(WATEROPEN_PWM, speed);
    PWM_CmdEX(_getPWMx_Type(WATEROPEN_PWM), true);
}
